package jnpf.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.base.Pagination;
import jnpf.base.entity.DbBackupEntity;
import jnpf.base.mapper.DbBackupMapper;
import jnpf.base.service.DbBackupService;
import jnpf.config.ConfigValueUtil;
import jnpf.database.util.DataSourceUtil;
import jnpf.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 数据备份
 *
 * @author JNPF开发平台组
 * @version V3.1.0
 * @copyright 引迈信息技术有限公司
 * @date 2019年9月27日 上午9:18
 */
@Service
public class DbBackupServiceImpl extends ServiceImpl<DbBackupMapper, DbBackupEntity> implements DbBackupService {

    @Autowired
    private UserProvider userProvider;
    @Autowired
    private DataSourceUtil dataSourceUtils;
    @Autowired
    private ConfigValueUtil configValueUtil;

    @Override
    public List<DbBackupEntity> getList(Pagination pagination) {
        // 定义变量判断是否需要使用修改时间倒序
        boolean flag = false;
        QueryWrapper<DbBackupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().orderByAsc(DbBackupEntity::getSortCode);
        if (pagination.getKeyword() != null) {
            flag = true;
            queryWrapper.lambda().and(
                    t -> t.like(DbBackupEntity::getFileName, pagination.getKeyword())
                            .or().like(DbBackupEntity::getBackupDbName, pagination.getKeyword())
            );
        }
        //排序
        queryWrapper.lambda().orderByAsc(DbBackupEntity::getSortCode).orderByDesc(DbBackupEntity::getCreatorTime);
        if (flag) {
            queryWrapper.lambda().orderByDesc(DbBackupEntity::getLastModifyTime);
        }
        Page<DbBackupEntity> page = new Page<>(pagination.getCurrentPage(), pagination.getPageSize());
        IPage<DbBackupEntity> iPage = this.page(page, queryWrapper);
        return pagination.setData(iPage.getRecords(), page.getTotal());
    }

    @Override
    public DbBackupEntity getInfo(String id) {
        QueryWrapper<DbBackupEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(DbBackupEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void delete(DbBackupEntity entity) {
        if (entity != null) {
            //删除文件
            FileUploadUtils.removeFile(configValueUtil.getDataBackupFilePath(), entity.getFileName());
            this.removeById(entity.getId());
        }
    }

    @Override
    public void create(DbBackupEntity entity) {
        entity.setId(RandomUtil.uuId());
        entity.setSortCode(RandomUtil.parses());
        entity.setCreatorUserId(userProvider.get().getUserId());
        this.save(entity);
    }
}
